/** CSC 460/560 Real Time Operating Systems - Mantis Cheng
 *	Fall 2007
 *	
 *	@author Scott Craig
 *
 *	A driver for sending debugging messages from one radio
 *	to another. Delivery is not guaranteed.
 *
 *  NB!: Must be compiled with optimisation at least -O2
 */

#include "radio.h"
#include "uart.h"

#include <avr/io.h>
#include <avr/interrupt.h>

#define LED_D5_RED		0x80



/**
 *  Wait for radio packets and write the contents to UART.
 *  All of the work is done in the interrupt handler.
 */

 //THis used to be int main
void base_main()
{
    /** Disable default prescaler to make processor speed 8 MHz. */
    CLKPR = (1<<CLKPCE);
    CLKPR = 0x00;

    uart_init();
    radio_init((uint8_t) 110, 0xABBA, 1);

    // Init an LED on the key
    PORTD ^= LED_D5_RED;
    DDRD |= LED_D5_RED;

    Enable_Interrupt();

    uart_write("Connected\r\n", 11);

    for(;;);

   
}


static uint8_t radio_buf[PAYLOAD_BYTES];
/**
 * Interrupt service routine for when data arrives at the radio (incoming).
 */
ISR (INT4_vect)
{
    int i;
    int still_good;
    int len;
	uint8_t* buf_ptr;

    PORTD ^= LED_D5_RED;

    still_good = 1;
    len = 0;
    buf_ptr = radio_buf;

    // Dump the radio to the buffer
    for(i=0; i < PAYLOAD_BYTES; ++i)
    {
        *buf_ptr = radio_get_byte();
        
        if(still_good && *buf_ptr == 0)
        {
            len = i;
            still_good = 0;
        }

        ++buf_ptr; 
    }
    if(still_good) len = PAYLOAD_BYTES;

    // Write the string up to first nul
    uart_write(radio_buf, len);
}


